package cn.hchaojie.jd.service;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.hchaojie.jd.dao.ProductDao;
import cn.hchaojie.jd.domain.Product;

@Service
public class ProductService {
	private static final String REGEX = "\\[(\\*|\\d+) TO (\\d+|\\*)\\]";
			
	@Autowired
	private ProductDao dao;
	
	public Page<Product> search(
			String keyword, String category, String price, 
			Pageable pageable) {	// Pageable里面封装了分页和排序的参数
		
		BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
		
		// 根据关键字搜索
		if (!StringUtils.isEmpty(keyword)) {
			// 用户输入条件比较长的情况
			// 先分词再搜索
			QueryStringQueryBuilder builder1 = QueryBuilders.queryStringQuery(keyword)
				.field("name", 2)		// 提高名称域的搜索权重
//				.field("description")
				// .analyzer("ik_smart")	// 指定分词器，如果不指定，用映射里面指定的
				.defaultOperator(Operator.OR);
			
			// 当用户输入的关键词比较短的情况，还得加一个wildcard query
			WildcardQueryBuilder builder2 = QueryBuilders.wildcardQuery("name", "*" + keyword + "*");
//			builder2.boost(14);
//			
			WildcardQueryBuilder builder3 = QueryBuilders.wildcardQuery("description", keyword);
//			builder3.boost(14);
//			
			BoolQueryBuilder keywordQueryBuilder = QueryBuilders.boolQuery()
					.should(builder1)
					.should(builder2)
					.should(builder3);
			
			queryBuilder.must(keywordQueryBuilder);
		}
		
		// 根据分类搜索
		if (!StringUtils.isEmpty(category)) {
			TermQueryBuilder categoryQueryBuilder = QueryBuilders.termQuery("category", category);
			queryBuilder.must(categoryQueryBuilder);
		}
		
		// 根据价格搜索 [* TO 9] [10 TO 19] [50 TO *]  
		if (!StringUtils.isEmpty(price)) {
			if (price.matches(REGEX)) {
				QueryStringQueryBuilder priceQuerybBuilder = QueryBuilders.queryStringQuery(
						"price:" + price);
				
				queryBuilder.must(priceQuerybBuilder);
			} else {
				throw new RuntimeException("价格不符合范围格式！");
			}
		}
		
		return dao.search(queryBuilder, pageable);
	}
	
	
}
